import { sdk } from "./src/demo";
import * as Koa from "koa";
import * as https from "https";
import * as fs from "fs";
import * as path from "path";
import * as Router from "koa-router";
import * as bodyParser from "koa-bodyparser"; // 处理post请求，把 koa2 上下文的表单数据解析到 ctx.request.body 中

async function main() {
  const host: number = 1234;
  const privateKey: string = fs.readFileSync(path.join(__dirname, "./src/ssl/2_www.chengsancai.xyz.key"), 'utf-8');
  const certificate: string = fs.readFileSync(path.join(__dirname, './src/ssl/1_www.chengsancai.xyz_bundle.crt'), 'utf8');
  const credentials = {
    key: privateKey,
    cert: certificate
  }

  // 支付宝sdk
  const alipaySdk = sdk();
  // Koa实例
  const app = new Koa();
  // Koa-router
  const router = new Router();

  app.use(bodyParser());

  router.post('/getUserToken', async (ctx, next) => {
    const authCode = ctx.request.url.substring(ctx.request.url.indexOf("=") + 1);
    console.log(authCode);

    // 获取授权访问令牌
    const result: any = await alipaySdk.exec('alipay.system.oauth.token', {
      grantType: 'authorization_code',
      code: authCode
    });

    console.log(result);

    // 用户唯一Id
    const userId: string = result.userId;
    // 用于获取用户信息
    const accessToken: string = result.accessToken;
    // 支付宝用户Id
    const alipayUserId: string = result.alipayUserId;

    const userInfo = await alipaySdk.exec("alipay.user.info.share", {
      authToken: result.accessToken
    });

    console.log(userInfo);
    ctx.set("Content-Type", "application/json");
    ctx.body = JSON.stringify(userInfo);
  });

  app.use(router.routes());

  https.createServer(credentials, app.callback()).listen(host, () => {
    console.log("服务器启动成功端口号:", host);
  });

}

main();